<script>
import Vue from "vue/dist/vue.min.js";
import cloneDeep from "lodash/cloneDeep";
import { exportDefault } from "@/utils/index";
import parser from "@/components/parser";
import { makeUpHtml } from "@/components/generator/html";
import { makeUpJs } from "@/components/generator/js";
import { makeUpCss } from "@/components/generator/css";
// import templateComponent from "@/components/common/templateComponent";
const uaParser = require("ua-parser-js");

import * as API from "@/api/index";
import * as wxAPI from "@/api/wx";
import { isMobile } from "@/utils/tools";

const ua = uaParser(navigator.userAgent);

export default {
  name: "Home",
  components: { parser },
  data() {
    return {
      projectKey: undefined,
      formData: null,
      formLogic: [], // 逻辑
      htmlCode: "",
      jsCode: "",
      cssCode: "",
      allCode: "",
      currentComponent: "template-component",
      submitLoading: false,
      containerStyle: {},
      wxUserInfo: null,
    };
  },
  async mounted() {
    this.setDevice();
    const projectKey = this.$route.query.key || "4120";
    this.projectKey = projectKey;
    await this.getFormLogic();
    await this.getFormData();
  },
  methods: {
    setDevice() {
      if (isMobile()) {
        this.containerStyle = {
          backgroundColor: "#fff",
        };
      } else {
        this.containerStyle = {
          width: "800px",
          margin: "auto auto",
          backgroundColor: "#fff",
          padding: "20px 40px",
        };
      }
    },
    onlyWxOpenHandle() {
      let wxUa = navigator.userAgent.toLowerCase();
      let isWeixin = wxUa.indexOf("micromessenger") != -1;
      if (!isWeixin) {
        document.head.innerHTML =
          '<title>抱歉，出错了</title><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0"><link rel="stylesheet" type="text/css" href="https://res.wx.qq.com/open/libs/weui/0.4.1/weui.css">';
        document.body.innerHTML =
          '<div class="weui_msg"><div class="weui_icon_area"><i class="weui_icon_info weui_icon_msg"></i></div><div class="weui_text_area"><h4 class="weui_msg_title">请在微信客户端打开链接</h4></div></div>';
      }
    },
    async getFormData() {
      try {
        const resp = await API.getFormData(this.projectKey);
        const respSetting = await API.fetchPrUserProjectSettingByProjectKey(
          this.projectKey
        );
        if (resp && resp.data && resp.data.code === "10000" && resp.data.data) {
          const formData = cloneDeep(resp.data.data.origin_data);
          this.formData = formData;

          // 检查表单是否是需要微信登录后才可以填写的
          if (
            respSetting.data.code === "10000" &&
            respSetting.data.data.is_wx_write === 1
          ) {
            this.onlyWxOpenHandle();
            const wxUserInfo = await this.getWxUserInfo();
            this.wxUserInfo = wxUserInfo;
            if (!(wxUserInfo && wxUserInfo.openid)) {
              // 未登录 跳转到微信公众号登录页面
              this.$confirm("是否登录本公众号?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then((v) => {
                if (v === "confirm") {
                  this.$router.replace(`/wx/blankAuth?key=${this.projectKey}`);
                }
              });
              return;
            }
          }
          if (!(respSetting.data.code === "10000" && resp.data.code)) {
            this.$message({
              type: "error",
              message: "数据获取失败",
            });
            return;
          }
          this.createDynamicComponent();
        } else {
          this.$message({
            type: "warning",
            message: "表单已经下线了哦！",
          });
        }
      } catch (error) {
        console.log(error);
      }
    },
    async getFormLogic() {
      const resp = await API.fetchProjectLogicByProjectKey(this.projectKey);
      console.log("logic", resp);
      if (resp && resp.data && resp.data.code == "10000") {
        this.formLogic = resp.data.data || [];
      }
    },
    createDynamicComponent() {
      this.htmlCode = makeUpHtml(this.formData, "file");
      this.jsCode = makeUpJs(this.formData, "file").replace(exportDefault, "");
      this.cssCode = makeUpCss(this.formData);
      this.allCode = this.htmlCode + this.jsCode + this.cssCode;
      const main = eval(`(${this.jsCode})`); // 解析字符串为一个js对象
      main.template = `<div>${this.htmlCode}</div>`;
      main.name = "my-children";
      Vue.component("my-children", main);
      this.currentComponent = "my-children";
    },
    async myComponentSubmit(form) {
      console.log("submit form is:", JSON.stringify(form));
      this.submitLoading = true;
      console.log("form::", form);
      await API.submitForm({
        // 'completeTime': inActiveTime,
        projectKey: this.projectKey,
        submitOs: ua.os.name,
        submitBrowser: ua.browser.name,
        submitUa: ua,
        wxUserInfo: this.wxUserInfo,
        wxOpenId: this.wxUserInfo ? this.wxUserInfo.openid : "",
        originalData: form,
        processData: form,
      });

      setTimeout(() => {
        this.submitLoading = false;
        this.$router.replace("/success");
      }, 1500);
    },
    // 检查用户是否已经登录到公众号
    async getWxUserInfo() {
      try {
        const resp = await wxAPI.getWxUserInfo();
        return resp.data;
      } catch (error) {
        console.log(error);
      }
    },
  },
  render() {
    if (this.currentComponent !== "my-children") {
      return (
        <div class="__page_container">
          <div class="loading">加载中...</div>
        </div>
      );
    } else {
      // <my-children
      //   {...{
      //     attrs: { submitLoading: this.submitLoading },
      //     on: { ["submitForm"]: this.myComponentSubmit },
      //   }}
      // />
      return (
        <div class="__page_container" {...{ style: this.containerStyle }}>
          <parser
            {...{
              attrs: {
                submitLoading: this.submitLoading,
                formConf: this.formData,
                formLogic: this.formLogic,
              },
              on: { ["submit"]: this.myComponentSubmit },
            }}
          />
        </div>
      );
    }
  },
};
</script>
<style lang="scss" scoped>
.__page_container {
  font-size: 14px;
  padding: 20px;
  .loading {
    text-align: center;
    padding-top: 20px;
  }
}
</style>
